import { useState, useEffect, useMemo, useContext } from 'react'
import Tabs from '@material-ui/core/Tabs';
import Tab from '@material-ui/core/Tab';
import Article from '../../compoments/article';
import { getArticles, getMyArticles } from '../../api';
import { UserContext } from '../../layout/index'
export default function Home(props) {
    const [tabValue, setTabValue] = useState(0);
    const [articles, setArticles] = useState([]);
    const [myArticles, setMyArticles] = useState([])
    const handleChange = (event, newValue) => {
        setTabValue(newValue)
    };
    const getAllArticle = async () => {
        const { data: artilces } = await getArticles();
        const { data: myArticles } = await getMyArticles()
        setArticles(artilces); setMyArticles(myArticles)
    }
    useEffect(() => {
        getAllArticle()
    }, [])
    const renderArticle = useMemo(() => {
        switch (tabValue) {
            case 0:
                return articles?.map(article => <Article key={article['_id']} {...article} {...props}></Article>);
            case 1:
                return myArticles?.map(article => <Article key={article['_id']} {...article} {...props}></Article>);
            default:
                return <div>loading...</div>
        }

    }, [tabValue, articles, props, myArticles])
    const { username } = useContext(UserContext);
    return (
        <div>
            <Tabs value={tabValue} onChange={handleChange} aria-label="simple tabs example">
                <Tab label="全部" />
                {username && <Tab label="我发布的" />}
            </Tabs>
            {renderArticle}
        </div>
    );
}
